package cn.weekimwee.firstlineofcodeforkotlin.unit7

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.view.View
import cn.weekimwee.firstlineofcodeforkotlin.BaseActivity
import cn.weekimwee.firstlineofcodeforkotlin.R
import kotlinx.android.synthetic.main.activity_unit7.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

class Unit7Activity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_unit7)
        button.setOnClickListener { it.click() }
        start.setOnClickListener { it.click() }
    }

    private fun View.click() {
        when (this.id) {
            R.id.button -> {
                if (ContextCompat.checkSelfPermission(this@Unit7Activity, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this@Unit7Activity, arrayOf(Manifest.permission.CALL_PHONE), 1)
                } else {
                    call()
                }
            }
            R.id.start -> {
                startActivity<ContactActivity>()
            }
        }
    }

    private fun call() {
        startActivity(Intent(Intent.ACTION_CALL).apply {
            data = Uri.parse("tel:10086")
        })
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            1 ->
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    call()
                } else {
                    toast("没给权限")
                }
        }
    }
}
